/*
 * @Descripttion: redux核心模块之一：createStore模块
 * @Author: lukasavage
 * @Date: 2021-11-23 21:23:30
 * @LastEditors: lukasavage
 * @LastEditTime: 2021-11-27 11:47:34
 */

function createStore(reducer, preloadedState, enhancer) {
    let state = preloadedState,
        listeners = [];

    function getState() {
        return state;
    }

    function subscribe(listener) {
        listeners.push(listener);
        return () => {
            listeners = listeners.filter(item => item !== listener);
        }
    }

    function dispatch(action) {
        state = reducer(state, action);
        listeners.forEach(listener => listener());
    }

    dispatch({ type: '@@redux/init' });
    if (typeof enhancer !== 'undefined') {
        if (typeof enhancer !== 'function') {
            throw new Error('Expected the enhancer to be a function.')
        }

        return enhancer(createStore)(reducer, preloadedState)
    }

    return {
        getState,
        subscribe,
        dispatch
    }
}
export default createStore;